﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using bzxxxt.admin.entity;
using bzxxxt.dal;
namespace bzxxxt.admin.service
{
    public class RoleService : BaseService
    {
        public string getall()
        {
            var list = from b in DB.tbRole
                       select new RoleEntity
                       {
                           id = b.id,
                           name = b.name,
                           sort = b.sort,
                           description = b.description,
                           addDate = b.addDate,
                           modifyDate = b.modifyDate

                       };
            string json = JsonUtil.ToJson(list.ToList());
            return json;
        }

        public string search(int pageSize, int pageIndex, string order, string where = "id>1")
        {
            int totalCount = 0;
            SqlParameter paramTotalCount = new SqlParameter("@totalCount", totalCount);
            paramTotalCount.Direction = ParameterDirection.Output;
            var pager = DB.tbRole.SqlQuery("exec sp_Pager @tableName,@columns,@order,@pageSize,@pageIndex,@where,@totalCount output",
                GetPagerParameters("tbRole", "*", order, where, pageSize, pageIndex, paramTotalCount)).ToList();
            var list = from b in pager
                       select new RoleEntity
                       {
                           id = b.id,
                           name = b.name,
                           sort = b.sort,
                           description = b.description,
                           addDate = b.addDate,
                           modifyDate = b.modifyDate

                       };
            var l = list.ToList();
            totalCount = Convert.ToInt32(paramTotalCount.Value);
            string json = JsonUtil.ToJson(new { total = totalCount, rows = l });
            return json;
        }

        public string add(tbRole b)
        {
            DB.tbRole.Add(b);
            DB.SaveChanges();
            string json = JsonUtil.ToJson(new { success = true });
            return json;
        }

        public string edit(tbRole b)
        {
            var old = DB.tbRole.FirstOrDefault(m => m.id == b.id);
            old.name = b.name;
            old.sort = b.sort;
            old.modifyDate = b.modifyDate;
            old.description = b.description;

            DB.SaveChanges();
            string json = JsonUtil.ToJson(new { success = true });
            return json;
        }

        public string delete(string strIds)
        {
            if (string.IsNullOrEmpty(strIds))
            {
                return JsonUtil.ToJson(new { success = false, msg = "没有选择要删除的记录！" });
            }
            string[] arr = strIds.Split(',');
            List<int> ids = new List<int>();
            foreach (var id in arr)
            {
                ids.Add(int.Parse(id));
            }
            var buttons = DB.tbRole.Where(m => ids.Contains(m.id)).ToList();
            if (buttons != null)
            {
                buttons.ForEach(m => DB.tbRole.Remove(m));
                DB.SaveChanges();
                return JsonUtil.ToJson(new { success = true });
            }
            else
            {
                return JsonUtil.ToJson(new { success = false, msg = "删除失败！" });
            }
        }
        /// <summary>
        /// 给角色授权
        /// </summary>
        /// <param name="roleId">角色Id</param>
        /// <param name="menuIds">菜单Id列表</param>
        /// <param name="buttonIds">菜单对应的按钮Id列表</param>
        /// <returns></returns>
        public string authorize(int roleId, string menuIds, string buttonIds) {
            List<int> menuIdList = new List<int>();
            List<int> buttonIdList = new List<int>();
            if (!string.IsNullOrEmpty(menuIds))
            {
                string[] ids = menuIds.Split(',');
                foreach (string id in ids) {
                    menuIdList.Add(int.Parse(id));
                }
                ids = buttonIds.Split(',');
                foreach (string id in ids)
                {
                    buttonIdList.Add(int.Parse(id));
                }
            }
            //先删除原来的授权
            var list = DB.tbRoleMenuButton.Where(m => m.roleId == roleId).ToList();
            list.ForEach(m => DB.tbRoleMenuButton.Remove(m));
            for (int i = 0; i < buttonIdList.Count; i++) {
                DB.tbRoleMenuButton.Add(new tbRoleMenuButton {
                        roleId = roleId,
                        menuId = menuIdList[i],
                        buttonId = buttonIdList[i]
                    });
            }
            DB.SaveChanges();
            return JsonUtil.ToJson(new { success = true});
        }

        public string getUserByRoleId(int roleId) {
            var users = DB.tbRole.SingleOrDefault(m => m.id == roleId).tbUser
                .Select(b => new UserEntity {
                    id = b.id,
                    userName = b.userName,
                    userPwd = b.userName,
                    realName = b.realName,
                    points = b.points,
                    grade = b.grade,
                    addDate = b.addDate,
                    description = b.description,
                    able = b.able,
                    tel = b.tel,
                    roleIds = b.tbRole.Select(m => m.id),
                    roleNames = b.tbRole.Select(m => m.name),
                    deptIds = b.tbDepartment.Select(m => m.id),
                    deptNames = b.tbDepartment.Select(m => m.name)
                });
            return JsonUtil.ToJson(users);
        }
    }
}